<%@ page language="java" contentType="text/html; charset=utf8"
	pageEncoding="utf8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link type="text/css" href="resources/css/jquery-ui.css" 		rel="stylesheet" />
	<link type="text/css" href="resources/css/flexigrid.css" 		rel="stylesheet">
	<link type="text/css" href="resources/css/main.css" 			rel="stylesheet"/>
	<link type="text/css" href="resources/css/ui.jqgrid.css"  media="screen" 	rel="stylesheet" />
	
	<script type="text/javascript" src="resources/jquery.min.js"></script>
	<script type="text/javascript" src="resources/jquery-ui.min.js"></script>
	<script type="text/javascript" src="resources/flexigrid.js"></script>
	
	<script type="text/javascript" src="resources/i18n/grid.locale-en.js" ></script>
	<script type="text/javascript" src="resources/jquery.jqGrid.src.js" ></script>
	<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true"></script>
	<script type="text/javascript" src="resources/jquery.ui.map.full.min.js" ></script>
    <style>
    #toolbar {
        padding: 10px 4px;
    }
    
/*     #jqUserOrderList { */
/*         font-size: 20px; */
/*     } */
    
    </style>

<script type="text/javascript">
var currentItemId;
var currentRowData;

/*************************************************************/		
function download(orderId) {
	var type = "DOCX";
	// Retrieve download token
	// When token is received, proceed with download
	$.get('reports/download/token', function(response) {
		// Store token
		var token = response.message[0];
		// Show progress dialog
		$('#msgbox').text('Formare comenzii...');
		$('#msgbox').dialog( 
				{	title: 'Incarcare',
					modal: true,
					buttons: {"Inchide": function()  {
						$(this).dialog("close");} 
					}
				});
		// Start download 
		window.location = 'reports/download/report'+'?token='+token+'&type='+type+'&orderId='+orderId;
		//window.open = ('reports/download/report'+'?token='+token+'&type='+type);
		// Check periodically if download has started
		var frequency = 1000;
		var timer = setInterval(function() {
			$.get('reports/download/progress', {token: token}, 
					function(response) {
						// If token is not returned, download has started
						// Close progress dialog if started
						if (response.message[0] != token) {
							$('#msgbox').dialog('close');
							clearInterval(timer);
						}
				});
		}, frequency);
	});
};

function submitOrder(orderId){
		//alert('submit=' + orderId);
		  $.ajax({
          url : 'json/entity/userOrder/submit',
          type: 'POST',
          dataType : "json",
          data : {
        	  id : orderId
          		},
          success : function(data) {
        	  $("#jqUserOrderList").trigger("reloadGrid");
          		},
          error: function() {
         	            alert('A aparut o gresala');
         	        }   	          		
  	});
	};		
/*************************************************************/	

$(document).ready(function() { 
	$.ajaxSetup({cache:false});
	

	
	refreshBasketTotal();
	
	var initialized = [false,false,false];
	
    $(function() {
        $( "#mainMenu" ).tabs(
        		{
                    show: function(event, ui)
                        {
                            if(ui.index == 0 && !initialized[0])
                            {
                            	initAdvertizingGrid();
                                initialized[0] = true;
                            }
                            else if(ui.index == 1 && !initialized[1])
                            {
                            	initBasketGrid();
                                initialized[1] = true;
                            }
                            else if(ui.index == 2 && !initialized[2])
                            {
                            	initOrdersGrid();
                                initialized[2] = true;
                            }
                        }
                }		
        );
    });
    
	/* ------------------ BEGIN ADVERTISING GRID FUNCTION ----------------- */
	function initAdvertizingGrid(){
		  $("#listPrivate").jqGrid({
				jsonReader : {
				      root:"rows",
				      page: "page",
				      total: "total",
				      records: "records",
				      repeatitems: false,
				      id: "0"
				   },	  
			    url:'json/entity/b',
			    datatype: 'json',
			    mtype: 'POST',
			    ondblClickRow: function(rowid){showItemCard(rowid);},
			    colNames:['','#','Inv.№', 'Suport №','Foto','Tip suport','','AB','Region','Localitate', 'Adresa', 'Descriere amplasarii','Status', 'Pret',  'Latime','Inaltime','Dimensiuni', 'Liber'],
			    colModel :[ 
			      {name:'id', 					index:'id', 				width:20, hidden:true}, 
			      {name:'chk_itemSelected', 	index:'chk_itemSelected', 	width:20, formatter: checkBoxFormatter},     	  
//			       {name:'chk_itemSelected',index:'chk_itemSelected', width:15, align:"right",edittype:'checkbox',formatter: "checkbox",editoptions: { value:"True:False"},editable:true,formatoptions: {disabled : false}},
			        
			      {name:'inventarNr', 	   		index:'inventarNr', 		width:40, hidden:true, search:true},
			      {name:'supportNr',			index:'supportNr', 			width:50, hidden:true},
			      {name:'photo', 				index:'photo',				width:120, 
			    	  formatter: photoFormatter, sortable:false },      
			      {name:'supportTypeName',		index:'supportTypeName',	width:90, align:'center' },
			      {name:'light', 				index:'light',				width:25, align:'center',
			    	  formatter: lightFormatter, sortable:false, fixed:true },
			      {name:'AB', 	   				index:'AB', 				width:40,  align:'center', sortable:false, formatter: partFormatter},    	  
			      {name:'regionName', 			index:'regionName', 		width:90}, 
			      {name:'localityName', 		index:'localityName', 		width:100}, 
			      {name:'adress', 				index:'adress',				width:130, sortable:false},
			      {name:'locationDescription', 	index:'locationDescription',width:220},
			      {name:'status', 				index:'status',				width:30,  hidden:true },
			      {name:'price_base', 			index:'price_base',			width:45, 
			    	  formatter:priceFormatter , align:'center' },
			      {name:'width', 				index:'width',				width:45, sortable:false, hidden:true},
			      {name:'height', 				index:'height',				width:45, sortable:false, hidden:true},
			      {name:'dimension', 			index:'dimension',			width:70, sortable:false, fixed:true,
			    	  formatter: dimensionFormatter},
			      {name:'firstFreeDate', 				index:'firstFreeDate',				width:80, sortable:false}
			    ],
			    pager: '#pager',
			    toppager: true,
			    altRows: false,
			    rowNum:10,
			    rowList:[10,20,30],
			    sortname: 'id',
			    sortorder: 'asc',
			    viewrecords: true,
			    gridview: true,
			    autowidth: true,
			    height: 'auto',
			    caption: 'Suprafete publicitare',
			    search: true,
			    postData: 	{ filters:{	supportType:		function() { return $('#pSupportType').val(); }, 
									   	regionName: 		function() { return $('#pRegionName').val(); },
									   	localityName: 		function() { return $('#pLocalityName').val(); },
										addresString: 		function() { return $('#pAddresString').val(); },
									 	light: 				function() { return $('#pLight').is(':checked'); },
									 	priceFrom: 			function() { return $('#pPriceFrom').val(); },
									 	priceTo: 			function() { return $('#pPriceTo').val(); },
									 	freeOnDate:			function() { return $('#pFreeOnDate').val(); } 
										}
							}
			  });
		  
			  $("#basketContent").jqGrid({
					jsonReader : {
					      root:"rows",
					      page: "page",
					      total: "total",
					      records: "records",
					      repeatitems: false,
					      id: "0"
					   },	  
				    url:'json/entity/userBasket/listTotal',
				    datatype: 'json',
				    mtype: 'POST',
				    colNames:['Tip suport','Suma', 'Cantitate'],
				    colModel :[ 
				      {name:'supportTypeName',		index:'supportTypeName',	width:90, align:'center', sortable:false},
				      {name:'sum', 					index:'sum',				width:45, align:'center', sortable:false},
				      {name:'count', 				index:'count',				width:45, align:'center', sortable:false}
				    ],
				    pager: '#basket_pager',
				    altRows: false,
				    rowNum:10,
				    rowList:[10,20,30],
				    sortname: 'supportTypeName',
				    sortorder: 'asc',
				    viewrecords: true,
				    gridview: true,
				    autowidth: true,
				    height: 'auto',
				    caption: ''
				  }); 
		  
		  
	};
	/* ------------------ END ADVERTISING GRID FUNCTION ----------------- */
	/* ------------------ BEGIN BASKET GRID FUNCTION ----------------- */
	function initBasketGrid(){
		 $("#jqUserBasketList").jqGrid({
			jsonReader : {
			      root:"rows",
			      page: "page",
			      total: "total",
			      records: "records",
			      repeatitems: false,
			      id: "0"
			   },	  
		   url:'json/entity/userBasket',
		   datatype: 'json',
		   mtype: 'GET',
		   colNames:['#','Foto','Inv.№','Suport №', 'Tip suport','AB','Pret','Region','Localitate', 'Adresa','Incepere','Sfirsit', 'Bronare', 'Corectarea'],// 'Delete'],
		   colModel :[ 
		     {name:'id', 					index:'id', 				width:10, sortable:false },
		     {name:'photo', 				index:'photo',				width:120, formatter: photoFormatterBasket, sortable:false },      
		     {name:'advertisingRegistry.inventarNr', 	   	index:'advertisingRegistry.inventarNr', 	width:40, sortable:false },
		     {name:'advertisingRegistry.supportNr', 	   	index:'advertisingRegistry.supportNr', 	width:40, sortable:false, fixed:true, hidden:true},      
		     {name:'advertisingRegistry.supportTypeName',	index:'advertisingRegistry.supportTypeName',width:50, sortable:false },
		     {name:'AB', 	   				index:'AB', 				width:40,  align:'center', sortable:false, formatter: partFormatterBasket},
		     {name:'advertisingRegistry.price_base', 		index:'price_base',							width:45, formatter: priceFormatter , align:'center' , sortable:false },      
		     {name:'advertisingRegistry.regionName',		index:'advertisingRegistry.supportTypeName',width:80, sortable:false },
		     {name:'advertisingRegistry.localityName',		index:'advertisingRegistry.supportTypeName',width:80, sortable:false },
		     {name:'advertisingRegistry.adress', 	   		index:'advertisingRegistry.adress', 		width:100, sortable:false },
		     {name:'beginCommandDate',		index:'beginCommandDate', align:'center', width:50, sortable:false, editable: true},
		  	 {name:'endCommandDate', 	   	index:'endCommandDate', align:'center', width:50, sortable:false , editable: true },
		     {name:'reservationType', 	   	index:'reservationType', 		width:40, sortable:false,   hidden:true},
		     {name:'id', 					index:'id', 	width:60, align:'center', fixed:true, sortable:false, resize:false, formatter:'actions', formatoptions:{keys:true}}
		   ],
		   pager: '#pager',
		   toppager: true,
		   rowNum:10,
		   rowList:[10,20,30],
		   sortname: 'id',
		   sortorder: 'asc',
		   viewrecords: true,
		   gridview: true,
		   autowidth: true,
		   height: 'auto',
		   caption: 'Continutul cosului',
		   search: true,
		  	editurl : 'json/entity/userBasket/edit'
		 }); 		
		
	};
	/* ------------------ END BASKET GRID FUNCTION ----------------- */
	/* ------------------ BEGIN ORDERS GRID FUNCTION ----------------- */
	function initOrdersGrid(){
		  $("#jqUserOrderList").jqGrid({
				jsonReader : {
				      root:"rows",
				      page: "page",
				      total: "total",
				      records: "records",
				      repeatitems: false,
				      id: "0"
				   },	  
			    url:'json/entity/userOrder',
			    datatype: 'json',
			    mtype: 'GET',
			    colNames:['№','','Comanda №', 'Data comenzii', 'Trimite','Statutul comenzii',''],
			    colModel :[ 
			      {name:'id', 			index:'id', 					width:10, sortable:false },
			      {name:'id', 			index:'id', 					width:15, sortable:false,
			    	  formatter: printButtonFormatter},
			      {name:'orderNr',		index:'orderNr', 				width:40, sortable:false },   
			      {name:'orderDate',	index:'orderDate', 				width:40, sortable:false },
			      {name:'id', 			index:'id', 					width:90, align:'center', 
			    	  fixed:true, sortable:false, resize:false, formatter: submitFormatter},
			      {name:'orderStatus',	index:'orderStatus', 			width:40, sortable:false, formatter: statusFormatter },
			      {name:'id', 			index:'id', 					width:60, align:'center', 
							    	  fixed:true, sortable:false, resize:false, 
							    	  formatter:'actions', formatoptions:{keys:true,editbutton: false}}
			    ],
			    pager: '#pager',
			    toppager: false,
			    rowNum:10,
			    rowList:[10,20,30],
			    sortname: 'id',
			    sortorder: 'asc',
			    viewrecords: true,
			    gridview: true,
			    autowidth: true,
			    height: 'auto',
			    caption: 'Comenzile Dvs.',
			    search: true,
			    editurl : 'json/entity/userOrder/edit',
				    subGrid: true,
					caption: "Lista comenzilor Dvs.",
					// define the icons in subgrid
					subGridOptions: {
						"plusicon"  : "ui-icon-triangle-1-e",
						"minusicon" : "ui-icon-triangle-1-s",
						"openicon"  : "ui-icon-arrowreturn-1-e"
					},
					subGridRowExpanded: function(subgrid_id, row_id) {
						var subgrid_table_id, pager_id;
						subgrid_table_id = subgrid_id+"_t";
						pager_id = "p_"+subgrid_table_id;
						$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll' style=' font-size: 16px;'></table>");
						jQuery("#"+subgrid_table_id).jqGrid({
							jsonReader : {
							      root:"rows",
							      page: "page",
							      total: "total",
							      records: "records",
							      repeatitems: false,
							      id: "0"
							   },
							url:'json/entity/userOrderDetail?orderId=' + row_id,
							datatype: 'json',
							colNames: ['#','Inv. №','Foto','Inceput', 'Sfirsit', 'Reservare'],
							colModel: [
								{name:'id',index:'id',width:80,key:true, sortable:false },
								{name:'advertisingRegistry.inventarNr', 	   	index:'advertisingRegistry.inventarNr', 	width:100, sortable:false },
								{name:'photo', 				index:'photo',				width:120, formatter: photoFormatterBasket, sortable:false },      
								{name:'beginCommandDate',index:'beginCommandDate'	,width:120, sortable:false },
								{name:'endCommandDate',index:'endCommandDate'		,width:120, sortable:false },
								{name:'reservationType',index:'reservationType'		,width:180, sortable:false, formatter: reservationFormatter }
							],
						   	rowNum:20,
						   	sortname: 'num',
						    sortorder: 'asc',
						    height: '100%'
						});
					}
				
				
			}); 		
		
		
	};
	/* ------------------ END ORDERS GRID FUNCTION ----------------- */	
	
	
	/* ------------------ BEGIN  F O R M A T T E R S ----------------- */	
	 function checkBoxFormatter(cellvalue, options, rowObject) {
	  return "<input type='checkbox' id=cb_" + rowObject['id'] + ">"; 
	  };
	
	 function photoFormatter(cellvalue, options, rowObject) {
	  return "<img src='images/small/" + rowObject['inventarNr'] + "' width='120' alt='Фото' title='Фото' />";
	  };   
	 
	function photoFormatterBasket(cellvalue, options, rowObject) {
		return "<img src='images/small/" + (rowObject['advertisingRegistry'])['inventarNr'] + "' width='120' alt='Photo' title='PHOTO' />";
	};	  
	  
	
	
	 function priceFormatter(cellvalue, options, rowObject) {
	     return cellvalue + " \u20AC";
	 };   	 
	 
	 function lightFormatter(cellvalue, options, rowObject) {
	  if (rowObject['light']){
		  return "<img src='resources/icons/lightbulb_on.png' width='14' alt='+' title='+' />";
	  }  else {
		  return "<img src='resources/icons/lightbulb.png' width='14' alt='-' title='-' />";
	  }
	 };    
	 
	 function dimensionFormatter(cellvalue, options, rowObject) {
	  return rowObject['width'] + 'm.X' + rowObject['height']+'m.';
	 };     
	 
	 function partFormatter(cellvalue, options, rowObject) {
	  var inv = rowObject['inventarNr'];
	  var sup = rowObject['supportNr'];
	  return inv.replace(sup,'');
	 };

	  function partFormatterBasket(cellvalue, options, rowObject) {
		  var inv = (rowObject['advertisingRegistry'])['inventarNr'];
		  var sup = (rowObject['advertisingRegistry'])['supportNr'];
		  return inv.replace(sup,'');
	  };  
	 
	  function printButtonFormatter(cellvalue, options, rowObject) {
			return  "<input type='button'  value='Imprimare' onclick=\"download('"+rowObject['id']+"');\" />"; 
	  };
	  
	  function submitFormatter(cellvalue, options, rowObject) {
		  if (rowObject['orderStatus'] == 0 ){
			  var buName = "bt_"+rowObject['id'];
			  var ret ="<input type='button'  value='Trimite' onclick=\"submitOrder('"+rowObject['id']+"');\" />";
			  return ret;
		  } else {
			  return "";
		  }
		};
		
		function statusFormatter(cellvalue, options, rowObject) {
			if (cellvalue==0) return "Proect"; 
			if (cellvalue==1) return "Trimis";
			if (cellvalue==2) return "Acceptat";
			if (cellvalue==3) return "Refuzat";
		};	
		
		function reservationFormatter(cellvalue, options, rowObject) {
			if (cellvalue==0) return "Liber"; 
			if (cellvalue==1) return "Rezervat";
			if (cellvalue==2) return "Vindut cu contract";
		};		
	  
	 /* ------------------ END  F O R M A T T E R S ----------------- */
	 
	 /* ------------------ BEGIN DIALOG ----------------- */
	 function showItemCard(rowId) {
		var rowData = $("#listPrivate").getRowData(rowId);
		var colData = rowData['locationDescription'];
		currentItemId = rowId;
		currentRowData = rowData;
		$( "#itemDetail" ).dialog( "open" );
	 };
	 
     $( "#itemDetail" ).dialog({
         autoOpen: false,
         height: 600,
         width: 	900,
         resizable: false,
         modal: true,
         buttons: {
             "Adauga in cos": 	function() {
           	  addToBasket(this);
             	//$( this ).dialog( "close" );
             }
         },
         close: function() {
             //allFields.val( "" ).removeClass( "ui-state-error" );
         },
         open: function(){
             //var note_text = $('#pRegionName').attr('type');
            $("#cardItemId").html(currentRowData['id']);
            $("#cardInventarNr").html(currentRowData['inventarNr']);
            $("#cardSupportType").html(currentRowData['supportTypeName']);
            $("#cardLight").html(currentRowData['light']);             
            $("#cardWidthHeight").html(currentRowData['width'] + "m.X" + currentRowData['height'] + "m.");
            $("#cardPriceBase").html(currentRowData['price_base']);
            $("#cardRegionName").html(currentRowData['regionName']);	 
            $("#cardLocalityName").html(currentRowData['localityName']);
            $("#cardAdress").html(currentRowData['adress']);

            $("#cardLocationDescription").html(currentRowData['locationDescription']);
            $("#cardFirstFreeDate").html(currentRowData['firstFreeDate']);
            
            $("#cardTitle").html(currentRowData['inventarNr'] + "  &nbsp;&nbsp;&nbsp;&nbsp;" + 
           		 			  currentRowData['supportTypeName'] + "  &nbsp;&nbsp;&nbsp;&nbsp;" +
           		 			  currentRowData['width'] + "m.X" + currentRowData['height'] + "m.  &nbsp;&nbsp;&nbsp;&nbsp;" +
           		 			  currentRowData['light'] + "  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
           		 			  currentRowData['price_base'] + "  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
           		 			  currentRowData['firstFreeDate']);
            
            $("#cardLocation").html(currentRowData['localityName'] + "  " + 
		 			  				 currentRowData['adress']);
            
            $("#cardPhoto").attr('src',"images/big/" + currentRowData['inventarNr']);
            $("#map_canvas").gmap({ 'center': '47.013388,28.837698', 'zoom': 17 });
            
         }
     });
	/* ------------------ END DIALOG ----------------- */	 
	/* ------------------ BEGIN FILTERS FUNCTION ----------------- */	  
	$("#btResetFilter").click(function(){
		$("#pSupportType").val("");
		$("#pRegionName").val("");
		$("#pLocalityName").val("");
		$("#pAddresString").val("");
		$("#pLight").attr('checked', false);
		$("#pPriceFrom").val("");
		$("#pPriceTo").val("");
		$("#pFreeOnDate").val("");
		
		$("#listPrivate").trigger("reloadGrid");
	});
	
	$("#btApplyFilter").click(function(){
		$("#listPrivate").trigger("reloadGrid");
	});
	/* ------------------ BEGIN FILTERS FUNCTION ----------------- */	 	
	// BEGIN AUTOCOMPLETE functionality for filters panel
	 $("#pRegionName").autocomplete(
		       {
		           source : function(request, response) {
		               $.ajax({
		                   url : "public/distinct/region",
		                   dataType : "json",
		                   data : {
		                	   style: "full",
		                        maxRows: 12,
		                	   term : request.term
		                   },
		                   success : function(data) {
		                       response($.map(data , function(item) {
		                           return {
		                               label : item.regionName,
		                               value : item.regionName
		                           }
		                       }));
		                   }
		               });
		           },
		           minLength : 0
		       }).focus(function(e) {
		    	    if(!e.isTrigger) {
		    	    	$(this).autocomplete("search", "");
		    	    }
		    	    e.stopPropagation();
		       });			
	
	 
	 $("#pLocalityName").autocomplete(
		       {
		           source : function(request, response) {
		               $.ajax({
		                   url : "public/distinct/locality",
		                   dataType : "json",
		                   data : {
		                       term : request.term
		                   },
		                   success : function(data) {
		                       response($.map(data , function(item) {
		                           return {
		                               label : item.localityName,
		                               value : item.localityName
		                           }
		                       }));
		                   }
		               });
		           },
		           minLength : 0
		       }).focus(function(e) {
		    	    if(!e.isTrigger) {
		    	    	$(this).autocomplete("search", "");
		    	    }
		    	    e.stopPropagation();
		       });
	 
	 $("#pSupportType").autocomplete(
		       {
		           source : function(request, response) {
		               $.ajax({
		                   url : "public/distinct/supportType",
		                   dataType : "json",
		                   data : {
		                       term : request.term
		                   },
		                   success : function(data) {
		                       response($.map(data , function(item) {
		                           return {
		                               label : item.supportTypeName,
		                               value : item.supportTypeName
		                           }
		                       }));
		                   }
		               });
		           },
		           minLength : 0
		       }).focus(function(e) {
		    	    if(!e.isTrigger) {
		    	    	$(this).autocomplete("search", "");
		    	    }
		    	    e.stopPropagation();
		       });
//Add AUTOCOMPLETE functionality for filters panel	
	  function addToBasket(refDialog) {  
		  //alert($("#cardFirstFreeDate").html());
		  var requestAdd = 'json/entity/userBasket/add'; //?itemId=' + $("#cardItemId").html()+'&firstFreeDate=' + $("#cardFirstFreeDate").html();
		  $.ajax({
		          url : requestAdd,
		          dataType : "json",
		          data : {
		        	  itemId : $("#cardItemId").html(),
		        	  firstFreeDate : $("#cardFirstFreeDate").html()
		          		},
		          success : function(data) {
		        	  $("#jqUserBasketList").trigger("reloadGrid");
		        	  $("#basketContent").trigger("reloadGrid");
		        	  refreshBasketTotal();
		          		}
	      	});
		  $(refDialog).dialog( "close" );
	  };

	  $( "#submitAll").button().click(function() {
		  var rows= jQuery("#listPrivate").jqGrid('getRowData');
		  if (rows.length<1){ return;}
    	  var requestAdd = 'json/entity/userBasket/add';
    	  $(rows).each(function(i, row){
    		  var checkbox = $("#cb_" + row['id'], "#listPrivate");
		      if ($(checkbox).is(":checked")){
		    	  $.ajax({
		    	          url : requestAdd,
		    	          dataType : "json",
		    	          data : {
		    	        	  itemId : row['id'],
		    	        	  firstFreeDate :row['firstFreeDate'] },
		    	          success : function(data) {
		    	        	 	$(checkbox).removeAttr("checked").trigger('change');
		    	        	 	$("#jqUserBasketList").trigger("reloadGrid");
		    	      	 		$("#basketContent").trigger("reloadGrid");
		    	        	  	refreshBasketTotal(); }
		          	});  
			      }	
    	  });
	    });

	   $( "#pFreeOnDate" ).datepicker({
		   	dateFormat: "dd.mm.yy",
		   	autoSize: true,
		       changeMonth: true,
		       changeYear: true,
		       showOn: "button",
		       buttonImage: "resources/css/images/calendar.gif",
		       buttonImageOnly: true,
		       showButtonPanel: true,
		       defaultDate: "+1w"
		   });	
	   
	   function refreshBasketTotal() {
			  //$("#totalString").$("#cardAdress").html(currentRowData['adress']); 
			  $.getJSON('json/entity/userBasket/listSumTotal', function(data) {
				  $("#totalString").html("Total pe luna :  " + data + " \u20AC");
				});
		};	
	
	   $( "#checkBasketItems").button().click(function() {
	    	$.each($('#jqUserBasketList').jqGrid('getDataIDs'), 
	    			function(index, value) { 
	    		  		checkOneItem(value);
	    			}
	    	);
	    });
		   
		function checkOneItem(itemId){
		 	$("#checkResult").html("Checking...");
		    $.ajax({
		  	  url: 'json/entity/userBasket/checkItem',
		  	  dataType: 'json',
		  	  type: 'POST',
		  	  async: true,
		  	  data: {itemBasketId: itemId },
		  	  success: function(data, textStatus, jqXHR) {
		  		  		alert("Succes" + textStatus);
		  		 		$("#checkResult").html(data.itemChecked); },
		  	  error: function() {
		  	            alert('A aparut o gresala'); }     		  
		  	});
		};
			
		$( "#placeOrder").button().click(function() {
			if ($("#jqUserBasketList").getGridParam("reccount") <1 ){
				alert('Cosul e gol');
				return;
			}
		    $.ajax({
		   	  url: 'json/entity/userBasket/submit',
		   	  dataType: 'json',
		   	  type: 'GET',
		   	  async: true,
		   	  data: {},
		   	  success: function(data, textStatus, jqXHR) {
		   		  	alert("Succes - " + data.result);
		    		$("#jqUserBasketList").trigger("reloadGrid"); 
		    		$("#basketContent").trigger("reloadGrid");
		        	refreshBasketTotal(); 
		        	$("#jqUserOrderList").trigger("reloadGrid");},
		   	  error: function() {
		   	        alert('A aparut o gresala');
		   	        $("#jqUserBasketList").trigger("reloadGrid"); 
		   	     	$("#basketContent").trigger("reloadGrid");
		        	refreshBasketTotal();
		        	$("#jqUserOrderList").trigger("reloadGrid");}     		  
		   });
		});
		    
		$( "#clearBasket").button().click(function() {
			if ($("#jqUserBasketList").getGridParam("reccount") <1 ){
				return;
			}
		    $.ajax({
		   	  url: 'json/entity/userBasket/deleteAll',
		   	  dataType: 'json',
		   	  type: 'POST',
		   	  async: true,
		   	  data: {},
		   	  success: function(data, textStatus, jqXHR) {
		   		  	//alert("Succes" + data.result);
		    		$("#jqUserBasketList").trigger("reloadGrid");
		    		$("#basketContent").trigger("reloadGrid");
		        	refreshBasketTotal(); },
		   	  error: function() {
		   	        alert('Error occured');
		   	        $("#jqUserBasketList").trigger("reloadGrid");
		   	     	$("#basketContent").trigger("reloadGrid");
		        	refreshBasketTotal();}     		  
		   	});
		}); 
		
	
     
}); 
</script>	
<title>Comenzi on-line</title>
</head>
<body title="User's Main Form">
	<div id="header">
	  <div class="center">
	    <div id="logo">
	    <a href="#">STANDART</a>
	    </div>
	    <span style="float: right">
	    <table summary="main menu" cellpadding="0" border="0" cellspacing="0" class="ThemeMenuBar1MenuOuter">
			<tbody>
			<tr>
				<td><table class="ThemeMenuBar1Menu" cellspacing="0" cellpadding="0" border="0">
					<tbody><tr class="ThemeMenuBar1MainItem">
						<td class="ThemeMenuBar1MainItemText">
						<a href="http://www.standart.md/">
						<img width="32" src='resources/icons/home.png'  />
						</a>
						<a href="http://www.standart.md/contact.php">
						<img width="32" src='resources/icons/mail.png'  />
						</a>
						</td>
					</tr>
					</tbody>
					</table>
				</td>
				<td><table class="ThemeMenuBar1Menu" cellspacing="0" cellpadding="0" border="0">
					<tbody><tr>
						<td>
    		<a href="?language=ru"><img width="32" src='resources/icons/flag_russia.png'  /></a> 
    		<a href="?language=ro"><img width="32" src='resources/icons/flag_moldova.png' /></a>
						</td>
					</tr>
					</tbody>
					</table>
				</td>	
			</tr></tbody></table>	
		</span>
	  </div>
	</div>
	
	
	
	<a href="<c:url value="/logout" />"> Iesire din sistem </a> 
	
	<div id=mainMenu style="font-size: 0.9em;">	
		<ul>
	        <li><a href="#tabs-1">Registru spatiilor publicitare</a></li>
	       	<li><a href="#tabs-2">Cos</a></li>
	       	<li><a href="#tabs-3">Comenzi</a></li>
	    </ul>
		<div id="tabs-1">
			<div class="ui-jqgrid ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix"
						style="padding: .2em .2em .2em .2em;" >
				<span class="ui-jqgrid-title" style="font-size: 0.9em;">Parametrii de filtrare</span>
			</div>
			<div id="filtrationPanel" class="ui-userdata ui-state-default" style="padding: .2em .2em .2em .2em;">
				<table id="prm" style="width: 100%" border="0">
					<tr>
						<td align="right">Tipul suportului:</td>
						<td><input type="text" id="pSupportType" class="ui-widget"></td>
						<td>&nbsp;</td>
						<td align="right">Region:</td>
						<td><input type="text" id="pRegionName" class="ui-widget" ></td>
						<td>&nbsp;</td>
						<td align="right">Localitate:</td>
						<td colspan="2">
							<input type="text" id="pLocalityName"  class="ui-widget" >
							</td>
			<!-- 						<td>&nbsp;</td> -->
						<td align="right">&nbsp;</td>
						<td><input id="btApplyFilter" type="button" value="Filtreaza"></td>
					</tr>
					<tr>
						<td align="right">Liber la data:</td>
						<td><input type="text" id="pFreeOnDate" class="ui-widget"></td>						
						<td>&nbsp;</td>
						<td align="right">Adresa:</td>
						<td><input type="text" id="pAddresString" class="ui-widget"></td>
						<td>&nbsp;</td>
						<td align="right">Pret:</td>
						<td>
							<input type="text" id="pPriceFrom" class="ui-widget" size="7">
							<input type="text" id="pPriceTo"   class="ui-widget" size="7">
						</td>
						<td>Iluminare:</td>
						<td align="right"><input type="checkbox" id="pLight" ></td>
						<td><input id="btResetFilter" type="button" value="Curata filtru"></td>
					</tr>	
			
				</table> 
			</div>
			<br>
			<table style="width: 100%;" >
				<tr>
					<td align="center" width="100%" >
						<table id="listPrivate">
							<tr><td/></tr>
						</table>
					</td>
					<td align="center" valign="top"> 
						<div class="ui-jqgrid ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix"
							style="padding: .2em .2em .2em .2em;width: 250px;" >
						<span class="ui-jqgrid-title" style="font-size: 0.9em;">Continutul cosului:</span>
						</div>
						<div id="basketPanel" 
							class="ui-userdata ui-state-default" 
							style="padding: .2em .2em .2em .2em; height: 150px;">
							<table id="basketContent">
								<tr><td/></tr>
							</table>
							<span id="totalString"></span>	
						 </div>
						<div><button id="submitAll">Adauga in cos</button></div>
						<div id="hiddenDiv"></div>
			 		</td>
				</tr>
			</table>
			<div id="pager"></div>
			<div id="itemDetail" title="Detalizare suprafetei publicitare" style="font-size: 0.9em;">
				<table style="width: 100%;">
					<tr><td colspan="2"><div id="cardTitle" align="left" ></div></td></tr>
					<tr><td colspan="2"><div id="cardLocation" align="left" ></div></td></tr>		
					<tr>
						<td><a> <img id="cardPhoto" src='' width="500" alt='Foto' title='FOTO' /></a></td>
						<td>
						<div id="cardItemId" hidden="hidden" ></div>
						<div id="cardFirstFreeDate" hidden="hidden" ></div>
						
						<div id="map_canvas" style="width:350px;height:350px"></div>
						</td>		
					</tr>
					
					<tr><td colspan="2" align="left">Descriere amplasarii:		</td></tr>
					<tr><td colspan="2"><div id="cardLocationDescription"></div></td></tr>
				</table>
			</div>
		
		</div>
		<div id="tabs-2">
			<span id="toolbar" class="ui-widget-header ui-corner-all">
			    <button id="checkBasketItems" style="visibility: hidden;">Check Items</button>
			    <button id="clearBasket">Curata cos</button>
			    <button id="placeOrder">Plaseaza comanda</button>
			    
			</span>
				<div id="checkResult"></div>
			<table id="jqUserBasketList">
				<tr><td/></tr>
			</table>
		</div>
		<div id="tabs-3">
			<table id="jqUserOrderList">
				<tr><td/></tr>
			</table>
			<div id='msgbox' title='' style='display:none'></div>		
		</div>				
	</div>

</body>
</html>